CXX = g++
CXXFLAGS ?= -g -Wall -W -pedantic -Iinclude -Iother/UnitTest++/src -fpermissive -O2
LDFLAGS ?=
SED = sed
MV = mv
RM = rm

.PHONY: all header footer clean
.SUFFIXES: .o .cpp

lib = lib/libhenkocpp.a
test = bin/TestProject
perf = bin/PerformanceTest
libunittest=other/UnitTest++/lib/libunittest.a

src = \
	src/Exception.cpp \
	src/Pointer.cpp \
	src/HenkoString.cpp
	
objects = $(patsubst %.cpp, %.o, $(src))
dependencies = $(subst .o,.d,$(objects))

test_src = \
	test/main.cpp \
	test/tools.cpp \
	test/TestPointer.cpp
	
test_objects = $(patsubst %.cpp, %.o, $(test_src))
test_dependencies = $(subst .o,.d,$(test_objects))
	
perf_src = \
	perf/main.cpp
	
perf_objects = $(patsubst %.cpp, %.o, $(perf_src))
perf_dependencies = $(subst .o,.d,$(perf_objects))

define make-depend
  $(CXX) $(CXXFLAGS) -M $1 | \
  $(SED) -e 's,\($(notdir $2)\) *:,$(dir $2)\1: ,' > $3.tmp
  $(SED) -e 's/#.*//' \
      -e 's/^[^:]*: *//' \
      -e 's/ *\\$$//' \
      -e '/^$$/ d' \
      -e 's/$$/ :/' $3.tmp >> $3.tmp
  $(MV) $3.tmp $3
endef

all: header $(test) $(perf) footer

header: 
	@echo -----------------------------------------------
	@echo "              Henko's C++ Library "
	@echo -----------------------------------------------
	mkdir -p bin
	mkdir -p lib
	
$(libunittest):
	@echo -----------------------------------------------
	@echo Building UnitTest++ library ...
	cd other/UnitTest++; make
	@echo Done.
	@echo -----------------------------------------------
	
$(lib): $(objects) 
	@echo Creating $(lib) library...
	@ar cr $(lib) $(objects)
	@echo Done.
	@echo -----------------------------------------------

$(test): $(libunittest) $(lib) $(test_objects)
	@echo Linking $(test)...
	@$(CXX) $(LDFLAGS) -o $(test) $(test_objects) $(lib) $(libunittest)
	@echo Done.
	@echo -----------------------------------------------
	@echo Running unit tests...
	@./$(test)
	@echo Done.
	@echo -----------------------------------------------
	
$(perf): $(lib) $(perf_objects)
	@echo Linking $(perf)...
	@$(CXX) $(LDFLAGS) -o $(perf) $(perf_objects) $(lib)
	@echo Done.
	
	@echo -----------------------------------------------
	
footer: 
	@echo Make successfull.

clean:
	-@$(RM) $(objects) $(test_objects) $(perf_objects) $(dependencies) $(test_dependencies) $(perf_dependencies) $(test) $(lib) $(perf) 2> /dev/null

%.o : %.cpp
	@echo Compiling $<...
	@$(call make-depend,$<,$@,$(subst .o,.d,$@))
	@$(CXX) $(CXXFLAGS) -c $< -o $(patsubst %.cpp, %.o, $<)

ifneq "$(MAKECMDGOALS)" "clean"
-include $(dependencies)
-include $(test_dependencies)
endif
